using System;
using System.Linq.Expressions;
using System.Windows.Controls;
using FluentSilverlight.Utility.Reflection;

namespace FluentSilverlight.Expressions.TextItems
{
    public class Watermarker
    {
        private readonly BindingInterceptor bindingInterceptor;
        private readonly WatermarkEvaluator watermarkEvaluator;

        public Watermarker(object model, string modelProperty, TextBox textBox, string watermark)
        {
            watermarkEvaluator = new WatermarkEvaluator(textBox, watermark);

            bindingInterceptor = new BindingInterceptor(model, modelProperty,
                new ValueDependencyObject(), new DependencyPropertyBinder(textBox, TextBox.TextProperty));
            bindingInterceptor.ModelValueChanged += BindingInterceptorModelValueChanged;
            bindingInterceptor.ViewValueChanged += BindingInterceptorViewValueChanged;
        }

        private void BindingInterceptorViewValueChanged(object sender, ViewValueChangedEventArgs e)
        {
            if (watermarkEvaluator.IsInWatermarkMode) return;
            bindingInterceptor.SetModelValue(e.Value ?? "");
            watermarkEvaluator.Evaluate();
        }

        private void BindingInterceptorModelValueChanged(object sender, ModelChangedEventArgs e)
        {
            bindingInterceptor.SetViewValue(e.Value);
            watermarkEvaluator.Evaluate();
        }
    }

    public class Watermarker<TModel> : Watermarker
        where TModel : class
    {
        public Watermarker(object model, Expression<Func<TModel, object>> textExpression, TextBox textBox, string watermark)
            : base(model, ReflectionHelper.GetAccessor(textExpression).Name, textBox, watermark)
        {
        }
    }
}